package com.ship.common.core.utils;


import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {

    /**
     * 发送http请求
     * @param requestUrl
     * @return
     */
    public static Object sendOkHttpClient(String requestUrl, String requestMethod, RequestBody body, Map<String, String> headers){
        if(headers == null){
            headers = new HashMap<>();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS) // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS) // 写入超时时间
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method(requestMethod, body != null ? body : null)
                .headers(Headers.of(headers))
                .build();
        try (Response response = client.newCall(request).execute()) { // 使用 try-with-resources 确保自动关闭响应体
            if (response.isSuccessful()) {
                System.out.println(response.header("X-Bce-Request-Id"));
                return response.body().string();
            } else {
                String errorMessage = response.header("X-Bce-Error-Message");
                String requestId = response.header("X-Bce-Request-Id");
                System.out.println("Request failed: " + response.code() + " - "
                        + response.message() + " - " + errorMessage + " - " + requestId);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 远程调用文件上传
     * @param requestUrl
     * @param tempUrl
     * @param file
     * @return
     */
    public static String fileUpload(String requestUrl, String tempUrl, MultipartFile file){
        String fileName = file.getOriginalFilename();
        String result = "";
        File sendFile = new File("/mnt/file/temp/"+"tmp-" + fileName + "");
        System.out.println("sendFile:"+sendFile);
        try {
            try{
                if(!sendFile.exists()){
                    sendFile.createNewFile();
                }
                file.transferTo(sendFile);
            }catch (Exception e){
                System.out.println("文件转换失败==========="+e.getMessage());
            }
            OkHttpClient httpClient = new OkHttpClient();
            MediaType mediaType = okhttp3.MediaType.parse(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE);


            okhttp3.RequestBody fileBody = okhttp3.RequestBody.create(mediaType, sendFile);
            okhttp3.RequestBody requestBody = new MultipartBody.Builder().
                    setType(MultipartBody.FORM)
                    .addFormDataPart("key", fileName)
                    .addFormDataPart("file", fileName, fileBody).build();

            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(requestUrl)
                    .addHeader("Content-Type", org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE)
                    .build();

            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(response.header("X-Bce-Request-Id"));
                result = response.body().string();
            }
        } catch (Exception e){
            System.out.println("文件上传异常=================="+e.getMessage());
        } finally {
            if (sendFile.exists()) {
                sendFile.delete();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "{\n" +
                "\t\"request_id\": \"123456789\",\n" +
                "\t\"callback_url\": \"http://www.xxxx.com/callback\",\n" +
                "\t\"cargo\": [{\n" +
                "\t\t\"cargo_code\": \"cid00001\",\n" +
                "\t\t\"on_port\": \"宁波港\",\n" +
                "\t\t\"on_date\": \"2023-12-10\",\n" +
                "\t\t\"on_payload\": \"100\",\n" +
                "\t\t\"off_port\": \"⻘岛港\",\n" +
                "\t\t\"off_date\": \"2024-02-10\",\n" +
                "\t\t\"off_payload\": \"100\",\n" +
                "\t\t\"knot\": \"17\",\n" +
                "\t\t\"route\": \"巴拿⻢运河\",\n" +
                "\t\t\"location\": \"eastern\",\n" +
                "\t\t\"trade_subject\": \"xxx\"\n" +
                "\t}, {\n" +
                "\t\t\"cargo_code\": \"cid00002\",\n" +
                "\t\t\"on_port\": \"宁波港\",\n" +
                "\t\t\"on_date\": \"2024-05-10\",\n" +
                "\t\t\"on_payload\": \"150\",\n" +
                "\t\t\"off_port\": \"⻘岛港\",\n" +
                "\t\t\"off_date\": \"2024-09-10\",\n" +
                "\t\t\"off_payload\": \"150\",\n" +
                "\t\t\"knot\": \"17\",\n" +
                "\t\t\"route\": \"巴拿⻢运河\",\n" +
                "\t\t\"location\": \"eastern\",\n" +
                "\t\t\"trade_subject\": \"xxx\"\n" +
                "\t}, {\n" +
                "\t\t\"cargo_code\": \"cid00003\",\n" +
                "\t\t\"on_port\": \"宁波港\",\n" +
                "\t\t\"on_date\": \"2024-03-10\",\n" +
                "\t\t\"on_payload\": \"139\",\n" +
                "\t\t\"off_port\": \"⻘岛港\",\n" +
                "\t\t\"off_date\": \"2024-05-10\",\n" +
                "\t\t\"off_payload\": \"139\",\n" +
                "\t\t\"knot\": \"17\",\n" +
                "\t\t\"route\": \"巴拿⻢运河\",\n" +
                "\t\t\"location\": \"eastern\",\n" +
                "\t\t\"trade_subject\": \"xxx\"\n" +
                "\t}],\n" +
                "\t\"tankers\": [{\n" +
                "\t\t\"tanker_id\": \"tid10001\",\n" +
                "\t\t\"load\": \"123\",\n" +
                "\t\t\"gpm\": \"10\",\n" +
                "\t\t\"country\": \"xxxx\",\n" +
                "\t\t\"pre_off_date\": \"2023-10-24\",\n" +
                "\t\t\"next_on_date\": \"2025-01-01\",\n" +
                "\t\t\"trade_subject\": \"xxxxxxx\",\n" +
                "\t\t\"location\": \"eastern\"\n" +
                "\t}, {\n" +
                "\t\t\"tanker_id\": \"tid10002\",\n" +
                "\t\t\"load\": \"145\",\n" +
                "\t\t\"gpm\": \"10\",\n" +
                "\t\t\"country\": \"xxxx\",\n" +
                "\t\t\"pre_off_date\": \"2023-10-24\",\n" +
                "\t\t\"next_on_date\": \"2025-01-01\",\n" +
                "\t\t\"trade_subject\": \"xxxxxxx\",\n" +
                "\t\t\"location\": \"eastern\"\n" +
                "\t}, {\n" +
                "\t\t\"tanker_id\": \"tid10003\",\n" +
                "\t\t\"load\": \"156\",\n" +
                "\t\t\"gpm\": \"10\",\n" +
                "\t\t\"country\": \"xxxx\",\n" +
                "\t\t\"pre_off_date\": \"2023-10-24\",\n" +
                "\t\t\"next_on_date\": \"2025-01-01\",\n" +
                "\t\t\"trade_subject\": \"xxxxxxx\",\n" +
                "\t\t\"location\": \"eastern\"\n" +
                "\t}, {\n" +
                "\t\t\"tanker_id\": \"tid10004\",\n" +
                "\t\t\"load\": \"151\",\n" +
                "\t\t\"gpm\": \"10\",\n" +
                "\t\t\"country\": \"xxxx\",\n" +
                "\t\t\"pre_off_date\": \"2023-10-24\",\n" +
                "\t\t\"next_on_date\": \"2024-02-01\",\n" +
                "\t\t\"trade_subject\": \"xxxxxxx\",\n" +
                "\t\t\"location\": \"eastern\"\n" +
                "\t}]\n" +
                "}";
        JSONObject json = JSONObject.parseObject(s);
        System.out.println(json.toJSONString());
        RequestBody body = RequestBody.create(json.toJSONString(),MediaType.parse("application/json"));
        System.out.println(OkHttpUtil.sendOkHttpClient("http://106.12.241.246:8086/api/dispatch", "POST",body,null));
    }

}
